using System;
using System.Collections.Generic;
using System.Linq;
using AllIsWell.Core.Models;
using AllIsWell.Persistance;
using AllIsWell.Services.Infrastructure;

namespace AllIsWell.Services
{
    public class PageService : IPageService
    {
        private readonly IDestinyRepository _destinyRepository;
        private readonly IPageRepository _pageRepository;
        private readonly IUnitOfWork _unitOfWork;

        public PageService(IUnitOfWork unitOfWork)
        {
            _destinyRepository = unitOfWork.DestinyRepository;
            _pageRepository = unitOfWork.PageRepository;
            _unitOfWork = unitOfWork;
        }

        public Page GetFreshPage(int destinyId)
        {
            var destiny = _destinyRepository.GetDestiny(destinyId);
            var reterospects = destiny.Whats  
                                        .Where(IsEnabledWhat)
                                        .Select(GetRetrospect);

            return new Page {Retrospects = new List<Retrospect>(reterospects), DateTime = DateTime.Today, Destiny = destiny };
        }

        private static bool IsEnabledWhat(What what)
        {
            return what.Enabled;
        }

        private static Retrospect GetRetrospect(What what)
        {
            return new Retrospect {What = what};
        }

        public Page CreatePage(Page page)
        {
            var addedPage = _pageRepository.AddPage(page);
            _unitOfWork.Save();
            return addedPage;
        }

        public bool IsTodaysPageExists(int destinyId)
        {
            var todaysPage = _pageRepository.GetPageForToday(destinyId);

            return todaysPage != null;
        }

        public Page GetTodaysPage(int destinyId)
        {
            return _pageRepository.GetPageForToday(destinyId);
        }
    }
}